<?php
// 应用公共文件

// 屏蔽notice错误
error_reporting(E_ERROR | E_WARNING | E_PARSE);

/**
 * @param $code
 * @param string $msg
 * @param array $data
 * @param string $url
 * @param int $httpStatus
 * @return \think\response\Json
 */
function writeJson($code, $msg = "error", $data = [], $url = "", $httpStatus = 200)
{
    $result = [
        'code' => $code,
        'msg'  => $msg,
        'data' => $data,
        'url'  => $url,
    ];

    return json($result, $httpStatus);
}

if (!function_exists('get_cate_list')) {
    //递归函数 实现无限级分类列表
    function get_cate_list($list, $pid = 0, $level = 0)
    {
        static $tree = [];
        foreach ($list as $row) {
            if ($row['pid'] == $pid) {
                $row['level'] = $level;
                $tree[]       = $row;
                get_cate_list($list, $row['id'], $level + 1);
            }
        }

        return $tree;
    }
}

if (!function_exists('get_tree_list')) {
    //引用方式实现 父子级树状结构
    function get_tree_list($list)
    {
        //将每条数据中的id值作为其下标
        $temp = [];
        foreach ($list as $v) {
            $v['son']       = [];
            $temp[$v['id']] = $v;
        }
        //获取分类树
        foreach ($temp as $k => $v) {
            $temp[$v['pid']]['son'][] = &$temp[$v['id']];
        }

        return isset($temp[0]['son']) ? $temp[0]['son'] : [];
    }
}

/**
 * 生成salt
 * @param bool $num
 * @return bool|string
 */
if (!function_exists('getRandKey')) {
    function getRandKey($num = false)
    {
        if ($num) {
            $randStr = str_shuffle('1234567890');

            return substr($randStr, 0, 6);
        } else {
            return substr(md5(mt_rand(0, 32).'0905'.md5(mt_rand(0, 32)).'0123'), 10, 6);
        }
    }
}


if (!function_exists('check_auth')) {
    /**
     * 鉴权方法
     * @param $url
     * @return bool
     */
    function check_auth($url)
    {
        $auth = new \liliuwei\think\Auth();

        // 如果是超级管理员就不用鉴权
        if (session('session_admin.is_admin') == 1) {
            return true;
        } else {
            return $auth->check($url, session('session_admin.id'));
        }
    }
}
